function Game(el) {
    this.el = document.querySelector(el)

    // 搞地图
    this.map = new Map(this.el)
    this.map.create()

    // 搞食物
    this.food = new Food(this.el)
    this.food.create()

    // 搞蛇
    this.snake = new Snake(this.el)
    this.snake.create()
}



Game.prototype.start = function() {
    document.querySelector('.start').disabled = true
    
    this.t = setInterval(() => {
        // 蛇动
        this.snake.move()
        // // 检测是否撞墙
        // this.checkMap()
       

        // 判断吃食
        let snakeX = this.snake.snakeObj[0].x * 20
        let snakeY = this.snake.snakeObj[0].y * 20
        let foodX = this.food.foodX
        let foodY = this.food.foodY

        if(snakeX == foodX && snakeY == foodY) {
            let last = this.snake.snakeObj[this.snake.snakeObj.length - 1]

            this.snake.snakeObj.push({
                x:last.x,
                y:last.y,
                color:last.color,
                el:null
            })
            this.snake.create()  // 重新绘制蛇
            // 食物动
            this.food.move()
        }
        // if (snakeX == -20 || snakeX == this.el.clientWidth || snakeY == -20 || snakeY == this.el.clientHeight) {
        //     // console.log("撞墙了");
        //     alert('游戏结束')
        //     // 游戏结束
        //     this.stop();
        // }

    },150)

    // 监控键盘上下左右键  来动态更改蛇的direction
    document.addEventListener('keydown',(e) => {
        // 获取事件对象
        e = e || window.event
        // 获取键盘
        // console.log(e.keyCode)// 38 40 37 39 上下左右

        switch (e.keyCode) {
            case 38:
                this.snake.direction = "top"
                break;
            case 40:
                this.snake.direction = "bottom"
                break;
            case 37:
                this.snake.direction = "left"
                break;
            case 39:
                this.snake.direction = "right"
                break;
            default:
                break;
        };
    })
}

// 结束游戏
Game.prototype.stop = function() {
    Game.prototype.stop = function() {
        // 清除定时器
        clearInterval(this.t)
        document.querySelector('.start').disabled = false
    }
    
}